package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
      @Autowired
      private WeChatProperties weChatProperties;
       @Autowired
      private UserMapper userMapper;
      public static  final  String wx_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务,获取当前微信用户openid
        Map<String, String> paramMap=new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        String s = HttpClientUtil.doGet(wx_LOGIN, paramMap);
        //openid为空登录失败,抛出业务异常
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否新用户
         User user= userMapper.select(openid);
        //新用户,完成注册
         if(user==null){
              user= User.builder().openid(openid)
                     .createTime(LocalDateTime.now()).build();
              userMapper.insert(user);
         }
        //返回这个对象
        return user;
    }
}
